package org.xiaodongwei.jvm;

import org.xiaodongwei.config.HotSpotConfig;
import org.xiaodongwei.jvm.exe.JVMStackFrame;
import org.xiaodongwei.jvm.load.BootstrapClassLoader;
import org.xiaodongwei.jvm.thread.JVMThread;
import org.xiaodongwei.jvm.utils.Log;
import tech.medivh.classpy.classfile.ClassFile;
import tech.medivh.classpy.classfile.MethodInfo;

import java.io.File;
import java.util.Arrays;

/**
 * Java虚拟机
 */
@SuppressWarnings("all")
public class HotSpot {
    private static final String TAG = "HotSpot";

    private String mainClassFullName;           // 需要加载的主类

    private BootstrapClassLoader classLoader;   // 类加载器

    public HotSpot(String mainClassFullName, String classPath) {
        this.mainClassFullName = mainClassFullName;
        this.classLoader = new BootstrapClassLoader(Arrays.asList(classPath.split(File.pathSeparator)));
    }

    public void start() throws Exception {
        // 将class转化为类对象
        ClassFile mainClassFile = classLoader.loadClass(mainClassFullName);

        // 获取当前类对象的主方法，也就是我们所谓的main函数，这个是整个调用的入口
        MethodInfo mainMethod = mainClassFile.getMainMethod();

        // 创建main栈，并将main帧入栈
        JVMStackFrame mainFrame = new JVMStackFrame(mainMethod, mainClassFile.getConstantPool());

        // 创建JVM线程，启动JVM线程，开始程序的调用过程
        JVMThread jvmThread = new JVMThread("main", mainFrame, classLoader);
        jvmThread.start();
    }
}
